﻿using AutoMapper;
using HandyControl.Data;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows;
using TransformerManager.Shared.Dto.Transformer;
using TransformerManager.Shared.Helper.HttpParams;
using TransformerManager.Shared.ResourceParameters;
using TransformerManager.WPF.Common.Http;
using TransformerManager.WPF.Common.Http.Service;

namespace TransformerManager.WPF.Common.ViewModels
{
    public class ProjectListTemplateViewModel : BindableBase, INavigationAware
    {
        private readonly ITransformerService _transformerService;

        private TransformerResourceParameters _trResourceParams;

        public ProjectListTemplateViewModel(
            ITransformerService transformerService)
        {
            _transformerService = transformerService;

            InitAllCmd();
        }


        #region Command

        public DelegateCommand<FunctionEventArgs<int>> PageUpdatedCmd { private set; get; }

        #endregion


        #region 方法的定义


        private ObservableCollection<TransformerDto> _showTrDataList
            = new ObservableCollection<TransformerDto>();
        public ObservableCollection<TransformerDto> ShowTrDataList
        {
            set
            {
                _showTrDataList = value;

                RaisePropertyChanged();
            }
            get
            {
                return _showTrDataList;
            }
        }

        private Visibility _isShowPaginationAndDataGrid
            = Visibility.Collapsed;
        public Visibility IsShowPaginationAndDataGrid
        {
            set
            {
                _isShowPaginationAndDataGrid = value;

                RaisePropertyChanged();
            }

            get
            {
                return _isShowPaginationAndDataGrid;
            }
        }

        private Visibility _isShowTip
            = Visibility.Visible;
        public Visibility IsShowTip
        {
            set
            {
                _isShowTip = value;

                RaisePropertyChanged();
            }

            get
            {
                return _isShowTip;
            }
        }

        private int _pageIndex = 1;
        public int PageIndex
        {
            set
            {
                _pageIndex = value;

                RaisePropertyChanged();
            }
            get
            {
                return _pageIndex;
            }
        }

        private int _maxPageCount;
        public int MaxPageCount
        {
            set
            {
                _maxPageCount = value;

                RaisePropertyChanged();
            }
            get
            {
                return _maxPageCount;
            }
        }

        private int _dataCountPerPage = 20;
        public int DataCountPerPage
        {
            set
            {
                _dataCountPerPage = value;

                RaisePropertyChanged();
            }

            get
            {
                return _dataCountPerPage;
            }
        }

        #endregion


        #region 函数的定义

        private void InitAllCmd()
        {
            PageUpdatedCmd = new DelegateCommand<FunctionEventArgs<int>>(async (curPageNum) =>
            {
                await PageUpdated(curPageNum);
            });
        }

        private async Task PageUpdated(FunctionEventArgs<int> curPageNum)
        {
            await RetrieveTrData(_trResourceParams, curPageNum.Info, _dataCountPerPage);
        }

        /// <summary>
        /// 获取变压器信息列表,并更新界面参数
        /// </summary>
        /// <param name="trResourceParams">过滤参数</param>
        /// <param name="pageIndex">当前页面数</param>
        /// <param name="pageSize">单页数据量</param>
        private async Task RetrieveTrData(
            TransformerResourceParameters trResourceParams,
            int pageIndex,
            int pageSize)
        {
            // 请求数据
            var resultWithHeaders = await _transformerService.GetTransformersAsync(trResourceParams, pageIndex, pageSize);

            if (resultWithHeaders == null || resultWithHeaders.Data.Count == 0)
            {
                ShowTrDataList.Clear();
                IsShowPaginationAndDataGrid = _showTrDataList.Count() == 0 ? Visibility.Collapsed : Visibility.Visible;
                IsShowTip = _showTrDataList.Count() == 0 ? Visibility.Visible : Visibility.Collapsed;
                return;
            }

            // 从响应中获取分页信息
            var headersParams = resultWithHeaders.Headers.Where(h => h.Key == "x-pagination").FirstOrDefault();
            var paginationParams = JsonConvert.DeserializeObject<PaginationParams>(headersParams.Value.FirstOrDefault());

            // 更新界面参数
            ShowTrDataList = new ObservableCollection<TransformerDto>(resultWithHeaders.Data);
            // 是否显示分页和表格
            IsShowPaginationAndDataGrid = _showTrDataList.Count() == 0 ? Visibility.Collapsed : Visibility.Visible;
            // 没有数据则显示提示
            IsShowTip = _showTrDataList.Count() == 0 ? Visibility.Visible : Visibility.Collapsed;
            // 每页数据量
            DataCountPerPage = paginationParams.PageSize;
            // 当前所出页码
            PageIndex = paginationParams.CurrentPage;
            // 最大页面数量
            MaxPageCount = paginationParams.TotalPages;
        }

        #endregion


        #region 接口的实现
        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {

        }

        public async void OnNavigatedTo(NavigationContext navigationContext)
        {

            _trResourceParams = navigationContext.Parameters
                .GetValue<TransformerResourceParameters>("TransformerResourceParameters");

            await RetrieveTrData(_trResourceParams, 1, _dataCountPerPage);
        }

        #endregion

    }
}
